/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.icybear.gae.pechapaii;

import net.icybear.gae.pechapaii.service.TwitterService;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;

/**
 *
 * @author Bearice
 */
@Controller
@RequestMapping("/timeline.wml")
public class Timeline {

    @Autowired
    private TwitterService twitterService;

    @RequestMapping
    public String timeline(HttpServletRequest req) {
        return timeline(req, 1, "home", null);
    }

    @RequestMapping(params = "timeline")
    public String timeline(HttpServletRequest req, String timeline, String name) {
        return timeline(req, 1, timeline, name);
    }

    @RequestMapping(params = {"page", "timeline"})
    public String timeline(HttpServletRequest req, int page, String timeline, String name) {
        try {
            Twitter twitter = twitterService.createTwitter(req);
            if (twitter == null) {
                return "wml/login";
            }
            ResponseList<Status> resp;
            if (timeline.equals("home")) {
                resp = twitter.getHomeTimeline(new Paging(page));
                req.setAttribute("timeline_name", "Home");
            } else if (timeline.equals("replies")) {
                resp = twitter.getMentions(new Paging(page));
                req.setAttribute("timeline_name", "Replies");
            } else if (timeline.equals("fav")) {
                resp = twitter.getFavorites(page);
                req.setAttribute("timeline_name", "Favorites");
            } else if (timeline.equals("friend")) {
                resp = twitter.getFriendsTimeline(new Paging(page));
                req.setAttribute("timeline_name", "Friends");
            } else if (timeline.equals("user")) {
                resp = twitter.getUserTimeline(name, new Paging(page));
                User u = twitter.showUser(name);
                req.setAttribute("user_info", u);
                req.setAttribute("timeline_name", "User[" + name + "]");
            } else {
                return "redirect:timeline.wml";
            }
            req.setAttribute("tweets", resp);
            req.setAttribute("page", page);
            req.setAttribute("timeline_url", req.getContextPath() + "/timeline.wml?timeline=" + timeline + (name != null ? "&name=" + name : ""));
            req.setAttribute("rateLimitStatus", resp.getRateLimitStatus());
            return "wml/timeline";
        } catch (TwitterException ex) {
            req.setAttribute("message", ex);
            return "wml/error";
        }
    }
}
